from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
import random
import redis

class SmsAPIView(APIView):
    def get(self,request):
        phone = request.query_params.get('phone')
        key = "sms_code:%s"%phone
        flag = "code:%s"%phone
        r = redis.Redis()
        if r.get(flag):
            r.close()
            return Response({'code':204,'err':'频繁生成验证码！'})
        yzm = random.randint(1000,9999)
        r.set(key,yzm,ex=300)
        r.set(flag,1,ex=60)
        r.close()
        return Response({'code':200,'msg':'生成验证码成功！','smsCode':yzm})
    def post(self,request):
        phone = request.data.get('phone')
        sms_code = request.data.get('smsCode')
        print(sms_code)
        key = "sms_code:%s"%phone
        r = redis.Redis()
        yzm = r.get(key)
        y = yzm.decode()
        print("???",y)
        if not yzm:
            r.close()
            return Response({'code':204,'err':'验证码已过期'})
        else:
            if y == sms_code:
                print(yzm.decode())
                r.close()
                return Response({'code':200,'msg':'验证码验证成功！'})
            else:
                r.close()
                return Response({'code':204,'msg':"验证码输入错误！"})




